package com.varian.auth.authentication.password;

import cn.hutool.core.map.MapUtil;
import com.varian.auth.constant.AuthConstant;
import lombok.Getter;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2AuthorizationGrantAuthenticationToken;
import org.springframework.util.Assert;

import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @author ben
 * @since 2024/6/25
 */
@Getter
public class OAuth2ResourceOwnerPasswordAuthenticationToken extends OAuth2AuthorizationGrantAuthenticationToken {

    private final Set<String> scopes;

    public OAuth2ResourceOwnerPasswordAuthenticationToken(
            Authentication clientPrincipal,
            Set<String> scopes,
            Map<String, Object> additionalParameters) {
        super(AuthConstant.PASSWORD, clientPrincipal, additionalParameters);
        Assert.notNull(clientPrincipal, "clientPrincipal cannot be null");
        this.scopes = Collections.unmodifiableSet((scopes != null) ? new HashSet<>(scopes) : Collections.emptySet());
    }

    public UsernamePasswordAuthenticationToken getUnauthenticatedToken() {
        String username = MapUtil.getStr(getAdditionalParameters(), OAuth2ParameterNames.USERNAME);
        String password = MapUtil.getStr(getAdditionalParameters(), OAuth2ParameterNames.PASSWORD);
        return UsernamePasswordAuthenticationToken.unauthenticated(username, password);
    }

}
